<template>
  <view class="sunui-uploader-bd flex">
    <u-upload
      :fileList="fileList"
      @afterRead="afterRead"
      @delete="deletePic"
      name="3"
      multiple
      :maxCount="10"
      :previewFullImage="true"
    >
      <!-- 设置其他样式 -->
      <!-- <image
        :style="{ width: width, height: height }"
        mode="widthFix"
        :src="src"
      ></image> -->
    </u-upload>
  </view>
</template>

<script>
export default {
  props: {
    // 样式路径 如果传入则改变他默认样式
    src: {
      type: String,
      default: null
    },
    // 宽度
    width: {
      type: String,
      default: '180rpx'
    },
    // 高度
    height: {
      type: String,
      default: '180rpx'
    },
  },
  data () {
    return {
      fileList: [],
      imgs: []
    }
  },
  name: 'upload-img',
  /**
   *  @$emit { change  deletePic }
   * 
   *  @change    新增图片 改变时会带出新增后的数组
   *
   *  @deletePic 删除图片 改变时会删除后的带出数组
   */
  methods: {
    // 删除图片
    deletePic (event) {
      this.imgs.splice(event.index, 1)
      this.fileList.splice(event.index, 1)
      this.$emit('deletePic', this.imgs)
    },
    // 新增图片
    async afterRead (event) {
      let lists = [].concat(event.file)
      let fileListLen = this.fileList.length
      lists.map((item) => {
        this.fileList.push({
          ...item,
          status: 'uploading',
          message: '上传中'
        })
      })
      for (let i = 0; i < lists.length; i++) {
        //  ！！！ 此方法对应common/upldata
        const res = await this.$updata(lists[i].url)
        if (res.code !== 200) return this.fileList = []
        let item = this.fileList[fileListLen]
        this.fileList.splice(fileListLen, 1, Object.assign(item, {
          status: 'success',
          message: '',
          // ！！！ this.$baseURl.imgUrl 对应common/baseUrl.js
          url: this.$baseURl.imgUrl + res.result
        }))
        fileListLen++
        this.imgs.push(res.result)
      }
      this.$emit('change', this.imgs)
    },
  }
};


</script>

<style lang="scss">
.sunui-uploader-bd {
  width: 100%;
}
</style>
